/**
 * Created by IntelliJ IDEA.
 * User: Madte
 * Date: 13.06.11
 * Time: 12:49
 * To change this template use File | Settings | File Templates.
 */
if (!ORYX.Plugins)
{
    ORYX.Plugins = new Object();
}
ORYX.Plugins.searchAndHighlight = Clazz.extend(
{
    excludedTags: Array.from(["defs", "text", "g", "a"]),
    facade: undefined,
    construct: function (facade)
    {
        this.facade = facade;
        this.facade.registerOnEvent(ORYX.CONFIG.EVENT_SHAPEADDED, this.getData.bind(this));
        this.facade.registerOnEvent(ORYX.CONFIG.EVENT_SHAPEDELETED, this.getData.bind(this));
        this.facade.registerOnEvent(ORYX.CONFIG.EVENT_PROPERTY_CHANGED, this.getData.bind(this));
        window.addEventListener("resize", this.handleWindowResize.bind(this), false);
        this.init();
    },
    init: function ()
    {
        this.comboWrapper = document.createElement('div'); // create div container used to position the combobox
        this.comboWrapper.setAttribute('id', 'pwave-combo');
        this.canvasContainer = $$(".ORYX_Editor")[0].parentNode;
        this.canvasContainer.appendChild(this.comboWrapper);
        this.store = new Ext.data.SimpleStore(
        {
            fields: ['name']
        });
         this.combo = new Ext.form.ComboBox(     // construct the combobox
        {
            store: this.store,
            displayField: 'name',
            valueField: 'name',
            hiddenName: 'name',
            typeAhead: true,
            mode: 'local',
            triggerAction: 'all',
            selectOnFocus: false,
            emptyText: 'Insert or select name',
            lazyInit: true,
            lazyRender: true,
            renderTo: 'pwave-combo',
            height: '45',
            validateOnBlur: false,
            maxHeight: '150'
        });

        this.getData;
    },
    setShadow: function setShadow(color, shape)                // set shadow for highlighting
    {
        var defsNode = this.facade.getCanvas().getDefsNode();
        this.createShadowFilter(color, defsNode);
        this.applyShadowFilter(color, shape);
    },
    existsShadowFilterFor: function existsShadowFilterFor(color, defsNode)
    {
        var filterNode;
        var defsNodeChildren = defsNode.children;
        // in Chrome .children can return undefined
        if (typeof defsNodeChildren !== "undefined")
        {
            for (var i = 0; i < defsNodeChildren.length; i++)
            {
                if (defsNodeChildren[i].id === color)
                {
                    filterNode = defsNodeChildren[i];
                    break;
                }
            }
        }
        return (typeof filterNode !== "undefined");
    },
    createShadowFilter: function createShadowFilter(color, defsNode)
    {
        if (this.isChrome())
        {
            //filterUnits does not work with chrome properly
            filterNode = ORYX.Editor.graft("http://www.w3.org/2000/svg", defsNode, ['filter', {
                "id": color
            }]);
        }
        else
        {
            filterNode = ORYX.Editor.graft("http://www.w3.org/2000/svg", defsNode, ['filter', {
                "id": color,
                "filterUnits": "userSpaceOnUse"
            }]);
        }
        ORYX.Editor.graft("http://www.w3.org/2000/svg", filterNode, ['feFlood', {
            "style": "flood-color:" + color + ";flood-opacity:0.8",
            "result": "ColoredFilter"
        }]);
        ORYX.Editor.graft("http://www.w3.org/2000/svg", filterNode, ['feGaussianBlur', {
            "in": "SourceAlpha",
            "stdDeviation": "1",
            "result": "BlurFilter"
        }]);
        ORYX.Editor.graft("http://www.w3.org/2000/svg", filterNode, ['feComposite', {
            "in": "ColoredFilter",
            "in2": "BlurFilter",
            "operator": "in",
            "result": "ColoredBlurFilter"
        }]);
        ORYX.Editor.graft("http://www.w3.org/2000/svg", filterNode, ['feOffset', {
            "in": "ColoredBlurFilter",
            "dx": "6",
            "dy": "6",
            "result": "FinalShadowFilter"
        }]);
        ORYX.Editor.graft("http://www.w3.org/2000/svg", filterNode, ['feMerge', {}, ['feMergeNode', {
            "in": "FinalShadowFilter"
        }],
            ['feMergeNode', {
                "in": "SourceGraphic"
            }]
        ]);
    },
    isChrome: function isChrome()
    {
      return false;
       /* if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1)
        {
            return true;
        }
        else
        {
            return false;
        }       */
    },
    applyShadowFilter: function applyShadowFilter(color, shape)   // apply shadow filter with "color" to "shape"
    {
        var svgNode = shape.node;
        var meNode = svgNode.getElementsByClassName("me")[0];
        var firstChild = meNode.firstChild;
        if (typeof firstChild !== "undefined")
        {
            if (shape instanceof ORYX.Core.Node)
            {
                var childNodes = firstChild.childNodes;
                for (var i = 0; i < childNodes.length; i++)
                {
                    var childNode = childNodes[i];
                    var tagName = childNode.tagName;
                    if ((typeof tagName !== "undefined") && !this.excludedTags.include(tagName))
                    {
                        childNode.setAttribute("filter", "url(#" + color + ")");
                    }
                }
            }
            else if (shape instanceof ORYX.Core.Edge)
            {
                if (!this.isChrome())
                {
                    //Chrome has problems with setting the bounding box for filters on edges
                    firstChild.setAttribute("filter", "url(#" + color + ")");
                }
            }
        }
    },
    getData: function getData()           // collects the data represented in the combobox
    {
        function isEmpty(obj)
        {
            for (var prop in obj)
            {
                if (obj.hasOwnProperty(prop)) return false;
            }
            return true;
        }
        var shapes = this.facade.getCanvas().getChildNodes(); //gets all child nodes of canvas
        var kpis = new Array();
        var temp = new Array();
        for (var i = 0; i < shapes.length; i++)    // get all kpis of each shape
        {
            temp = shapes[i].getChildNodes(false).findAll(function (node)
            {
                return (node.getStencil().id() === "http://b3mn.org/stencilset/pmanage#kpi");
            });
            for (var j = 0; j < temp.length; j++)
            {
                if (isEmpty(temp[j]) === false) kpis.push(temp[j]);
            }

        }

        this.facade.raiseEvent({

            "type": ORYX.CONFIG.EVENT_SEARCHANDHIGHLIGHT_KPILIST,
            "kpilist": kpis

        });

        var allshapes = shapes.concat(kpis); // put kpi and kpf/ksf list together

        var nameArray = new Array();
        var shapename;

        this.combo.on('select', function (combo, record, index)    // set shadow for selected shape in combobox
        {
            shapename = combo.getValue();
            for (var i = 0; i < allshapes.length; i++)
            {
                if (allshapes[i].properties["oryx-name"] === shapename)
                {
                    this.setShadow('#FF0000', allshapes[i]);
                }
            }
        }.bind(this));
        this.combo.on('blur', function ()             // remove shadow if the combobox looses focus
        {
            for (var i = 0; i < allshapes.length; i++)
            {
                if (allshapes[i].properties["oryx-name"] === shapename)
                {
                    this.facade.raiseEvent(
                    {
                        'type': ORYX.CONFIG.EVENT_SHAPE_METADATA_CHANGED,
                        'shape': allshapes[i]
                    });
                }
            }
        }.bind(this));

        for (var j = 0; j < allshapes.length; j++)    // make an array out of all shapenames
        {
            var shapename = allshapes[j].properties["oryx-name"];
            if (shapename)
            {
                if (nameArray.indexOf(shapename) === -1)
                {
                    nameArray.push([shapename]);
                }
            }
        }
        this.store.loadData(nameArray);     //load the store of the combobox with the nameArray

    },
    handleWindowResize: function handleWindowResize()    // manages the dynamic position of the combobox
    {
        this.comboWrapper.style.bottom = 0 + this.getCanvasScrollbarOffsetForHeight() + 'px';
        this.comboWrapper.style.right = 500 + this.getCanvasScrollbarOffsetForWidth() + 'px';
    },
    getCanvasScrollbarOffsetForWidth: function getCanvasScrollbarOffsetForWidth()
    {
        return this.canvasContainer.offsetWidth - this.canvasContainer.clientWidth;
    },
    getCanvasScrollbarOffsetForHeight: function getCanvasScrollbarOffsetForHeight()
    {
        return this.canvasContainer.offsetHeight - this.canvasContainer.clientHeight;
    }
});